package com.leyou.auth.service.impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author mySun
 * @create 2021-07-28 17:06
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void userLogin(String username, String password, HttpServletResponse response) {
        //调用user-service中的api处理登录业务
        UserDTO userDTO = userClient.queryUserByUsernameAndPassword(username, password);

        UserDetail userDetail = new UserDetail();
        userDetail.setId(userDTO.getId());
        userDetail.setUsername(userDTO.getUsername());
        String token = jwtUtils.createJwt(userDetail);

        Cookie cookie = new Cookie("LY_TOKEN",token);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setDomain("leyou.com");

        response.addCookie(cookie);

    }

    @Override
    public void userLogout(String token, HttpServletResponse response) {
        Payload payload = null;
        try {
            payload = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            //解析token有误，什么也不干
            return;
        }

        //删除cookie
        CookieUtils.deleteCookie("LY_TOKEN","leyou.com",response);

        jwtUtils.delete(payload.getUserDetail().getUsername());

    }
}
